package com.zzyl.Aop;

import com.zzyl.constant.UserCacheConstant;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.HttpStatus;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Set;

import static com.zzyl.constant.Constants.*;

@Aspect
@Component
@Slf4j
public class PermissionAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
     private  HttpServletResponse response;

    @Autowired
    private JwtTokenManagerProperties properties;

    @Autowired
    private StringRedisTemplate redisTemplate;



   @Before("@annotation(hasPermission)")
    public void bfefore(HasPermission hasPermission)throws  Exception{

       String token = request.getHeader((USER_TOKEN));
       if (StringUtils.isEmpty(token)) {
           return ;
       }
       try {
           Claims claims = JwtUtil.parseJWT(properties.getBase64EncodedSecretKey(), token);
           long userId = claims.get(JWT_USERID,Long.class);
           String username = claims.get(JWT_USERNAME, String.class);
           log.info("token中解析userId:{} username:{}", userId, username);
           // 从redis中获取用户有权限的url
          Set<String> urlList=redisTemplate.opsForSet().members(UserCacheConstant.USER_RESOURCE_LIST+ userId);
           String[] perms = hasPermission.perms();

           boolean qingdong = false;
           for (String perm : perms) {
               for (String s : urlList) {
                   if (perm.equals(s)){
                       qingdong = true;
                   }
               }
           }

           if (!qingdong){
               return;
           }
           UserThreadLocal.setSubject(""+userId);
       }catch (Exception e) {
           log.info(e.getMessage(), e);
           response.setStatus(HttpStatus.UNAUTHORIZED);
       }
   }
}




    // 鉴权的时候

    // before通知
    // 获取方法上的HasPermission，获取里面的values
    // 获取用户所拥有的所有的perms，看是否包含了法上的permission

    // 登陆的时候
    // 登录的时候，查询用户所有的perms，保存redis。

